package com.meteor.raft.cluster;

import com.alibaba.fastjson.JSON;
import com.meteor.raft.constant.CommonConstant;
import com.meteor.raft.core.RaftPeerManage;
import com.meteor.raft.misc.HttpClient;
import com.meteor.raft.misc.UrlUtil;
import com.meteor.raft.persistent.RaftData;
import com.meteor.raft.persistent.RaftPeer;
import com.meteor.raft.util.NetUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gang.wang1903@xiaobao100.cn
 * @Date: 2019/7/22 10:25 AM
 */
@Service
@Slf4j
public class ClusterServiceImpl implements ClusterService {

    @Autowired
    private RaftPeerManage raftPeerManage;

    @Autowired
    private NetUtils netUtils;

    @Autowired
    private RaftData raftData;

    @Override
    public Boolean publish(String key , String value) {

        RaftPeer local = raftPeerManage.getPeers().get(netUtils.localServer());
        log.info("start publish data: {}", value);
        Map<String, String> params = new HashMap<String, String>(1);
        params.put("key", key);
        params.put("value", value);
        //如果本身是leader，集群同步
        if(local.getState().name().equals(RaftPeer.State.LEADER.name())){
            for (final String server : raftPeerManage.allServersWithoutMySelf()) {
                final String url = UrlUtil.buildURL(server, CommonConstant.API_SAVE);
                try {
                    HttpClient.HttpResult result =  HttpClient.httpPost(url, null, params,"utf-8");
                    log.info("start publish cluster data: {}", value);
                    Boolean resultString = Boolean.valueOf(result.content);
                    log.info("finish publish cluster data: {}", resultString);
                } catch (Exception e) {
                    log.warn("error while publish to cluster: {}", server);
                }

            }
            //leader 本身数据更新
            log.info("save leader peer data: {}", value);
            raftData.saveData(key,value);
            //本身不是主节点，直接发送主节点
        }else {
            final String url = UrlUtil.buildURL(raftPeerManage.getLeader().getIp(), CommonConstant.API_PUBLISH);
            try {
                HttpClient.HttpResult result =  HttpClient.httpPost(url, null, params,"utf-8");
                log.info("start send data to leader: {}", value);
                Boolean resultString = Boolean.valueOf(result.content);
                log.info("finish send data to leader: {}", resultString);
            } catch (Exception e) {
                log.warn("error while publish to cluster: {}", raftPeerManage.getLeader().getIp());
            }
        }
        return true;
    }

    @Override
    public String getData(String key) {
        return null;
    }
}
